//
//  DBJAddIllCaseTableViewController.m
//  DBJ
//
//  Created by Captain_czq on 16/11/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "DBJAddIllCaseTableViewController.h"
#import "DBJAddIllCaseFirstTabCell.h"
#import "DBJAddIllCaseThreeTabCell.h"
#import "DBJAddIllCaseFourCell.h"
#import <HMImagePickerController.h>
#import "DBJIllCaseTagViewController.h"
#import "DBJIllTypeTabViewController.h"
#import "DBJIllTypeMinceViewController.h"
#import "DBJIllTypeMinceModel.h"
#import "DBJSecondTabModel.h"
@interface DBJAddIllCaseTableViewController ()<UITableViewDelegate,UITableViewDataSource,DBJAddIllCaseFourCellDelegate,HMImagePickerControllerDelegate,DBJAddIllCaseThreeCellDelegate,DBJIllCaseTagViewControllerDelegate,DBJAddIllCaseFirstTabCellDelegate,DBJIllTypeTabViewControllerDelegate,DBJIllTypeMinceViewControllerDelegate>

/* 标识符数组 */
@property(nonatomic,strong)NSArray *identArry;

/* 选中照片数组 */
@property(nonatomic,strong)NSArray *images;

/* 选中资源素材数组,用于定位已经选择的照片 */
@property(nonatomic,strong)NSArray *selectedAssets;

/* 病例细分url数据 */
@property(nonatomic,strong)NSArray *illMinceList;

/* 选中的病例 */
@property(nonatomic,assign)NSInteger selcetNum;

/* 添加seconde字典数组的模型 */
@property(nonatomic,strong)NSMutableDictionary *secondeModel;
/* 缓存路径 */
@property(nonatomic,copy)NSString *filePath;

/* sencond数组 */
@property(nonatomic,strong)NSMutableArray *illArry;

@end

@implementation DBJAddIllCaseTableViewController

- (void)dbjSetupSubviews{
    [super dbjSetupSubviews];
    
    //获取缓存路径docuPath	NSPathStore2 *	@"/Users/chenzhuqiu/Library/Developer/CoreSimulator/Devices/7D46FF2D-4E86-4758-8EDF-17FF916130CD/data/Containers/Data/Application/907B8CF5-E751-4DCD-85AB-0F7F8B289A5D/Documents"	0x00007f8c21742d30
//    self.illArry=[NSMutableArray array];NSDocumentDirectory
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES
    
    self.row=-666;
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
       self.filePath= [docuPath stringByAppendingPathComponent:@"ill.nb"];
   // NSLog(@"%@",self.filePath);
    //NSLog(@"xixi ");
    self.view.backgroundColor=[UIColor whiteColor];
    //实例标识符数组
   self.identArry=@[@"FirstCell",@"SecondCell",@"ThreeCell",@"FourCell"];
    NSArray *VCName=@[@"DBJAddIllCaseFirstTabCell",@"DBJAddIllCaseThreeTabCell",@"DBJAddIllCaseFourCell"];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self loadIllMinceData];
//    //注册xib
//    for(int i=0;i<3;i++){
    
//    [self registerXibWithName:VCName[0] andIdent:self.identArry[0]];
//    [self registerXibWithName:VCName[1] andIdent:self.identArry[1]];
//    [self registerXibWithName:VCName[2] andIdent:self.identArry[2]];
//    }
//    [self.tableView registerNib:[UINib nibWithNibName:VCName[0] bundle:nil] forCellReuseIdentifier:self.identArry[0]];
//    [self.tableView registerNib:[UINib nibWithNibName:VCName[1] bundle:nil] forCellReuseIdentifier:self.identArry[1]];
//    [self.tableView registerNib:[UINib nibWithNibName:VCName[2] bundle:nil] forCellReuseIdentifier:self.identArry[2]];
 
    //注册xib    //可优化 封装 参数cellName 字符串数组
    [self.tableView registerNib:[UINib nibWithNibName:VCName[0] bundle:nil] forCellReuseIdentifier:self.identArry[0]];
    [self.tableView registerNib:[UINib nibWithNibName:VCName[1] bundle:nil] forCellReuseIdentifier:self.identArry[2]];
    [self.tableView registerNib:[UINib nibWithNibName:VCName[2] bundle:nil] forCellReuseIdentifier:self.identArry[3]];

}
#pragma mark -封装注册cell的方法

-(void)registerXibWithName:(NSString *)name andIdent:(NSString *)ident{
    
    [self.tableView registerNib:[UINib nibWithNibName:name bundle:nil] forCellReuseIdentifier:ident];
}

#pragma mark -设置导航栏items

/* 设置导航栏items */
-(void)dbjSetupNavigationItems{
    [super dbjSetupNavigationItems];
    UIBarButtonItem *sure =[[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(clickSureitem:)];
    UIBarButtonItem *delete=[[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(clickDeleteitem:)];
    self.navigationItem.rightBarButtonItems=@[sure,delete];
}

#pragma mark -确定items方法

-(void)clickSureitem:(UIBarButtonItem *)sender{
    //先解档获取数组
    self.illArry=[NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    if(self.illArry==nil){
        self.illArry=[NSMutableArray array];
    }
    
    if(self.secondeModel[@"illType"]==nil){
         [DBJTools dbjShowSVErrorTitle:@"疾病类型不能为空" andTime:1];
        return ;
    }
   //将senconde字典转成模型对象
    DBJSecondTabModel *model=[[DBJSecondTabModel alloc]init];
    [model setValuesForKeysWithDictionary:self.secondeModel];
//    NSLog(@"%@-%@",model.illType,model.illMince);
    //归档
    [self.illArry addObject:model];
    //归档
    [NSKeyedArchiver archiveRootObject:self.illArry toFile:self.filePath];
    if([self.delegate respondsToSelector:@selector(popControllerWithVC:)]){
        [self.delegate popControllerWithVC:self];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark -删除items方法

-(void)clickDeleteitem:(UIBarButtonItem *)sender{
    if(self.row==-666){
        //NSLog(@"row=-666");
        [DBJTools dbjShowSVErrorTitle:@"内容未添加,请按确定" andTime:1];
        return ;
    }
    //根据传来的序号删除存储的对象
    //获取解档文件
    self.illArry=[NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    //删除对象
    [self.illArry removeObjectAtIndex:self.row];
    //归档
    [NSKeyedArchiver archiveRootObject:self.illArry toFile:self.filePath];
    if([self.delegate respondsToSelector:@selector(popControllerWithVC:)]){
        [self.delegate popControllerWithVC:self];
    }
    //pop控制器
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark -获取病例细分的数据

-(void)loadIllMinceData{
    
    NSURL *url=[[NSBundle mainBundle]URLForResource:@"illTypeUrl.plist" withExtension:nil];
    
    NSArray *list=[NSArray arrayWithContentsOfURL:url];
    
    NSMutableArray *arrM=[NSMutableArray arrayWithCapacity:list.count];
    for(NSDictionary *dict in list)
    {
        DBJIllTypeMinceModel *model=[[DBJIllTypeMinceModel alloc]init];
        [model setValuesForKeysWithDictionary:dict];
        [arrM addObject:model];
    }
    
    self.illMinceList=arrM.copy;
}

#pragma mark -实现添加病例界面数据源方法

/* 返回单元格的方法*/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.identArry.count;
}
 /*返回每组单元格的方法*/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //获取标识符
    NSString *identStr=self.identArry[indexPath.row];
    if(indexPath.row==0){
        //根据标识符创建cell
        DBJAddIllCaseFirstTabCell *cell=[tableView dequeueReusableCellWithIdentifier:identStr forIndexPath:indexPath];
        //设置cell的编号
        cell.cellType=CellTypeFirst;
         //设置代理对象
        cell.delegate=self;
        return cell;
    }else if(indexPath.row==1){
        DBJAddIllCaseFirstTabCell *cell=[tableView dequeueReusableCellWithIdentifier:@"FirstCell" forIndexPath:indexPath];
        cell.cellType=CellTypeSecond;
        cell.illTypeLabel.text=@"疾病细分";
        cell.delegate=self;
         return cell;
    }else if(indexPath.row==2){
        DBJAddIllCaseThreeTabCell *cell=[tableView dequeueReusableCellWithIdentifier:identStr forIndexPath:indexPath];
            UILabel * textLabel = [[UILabel alloc]initWithFrame:CGRectMake(3, 3, 300, 20)];
            textLabel.enabled = NO;
            textLabel.text = @"请在这里描述病情,添加病情请连续点击两次";
            textLabel.font =  [UIFont systemFontOfSize:15];
            textLabel.textColor = [UIColor lightGrayColor];
            [ cell.updatextView addSubview:textLabel];
             cell.testViewsubLabel=textLabel;
         UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickTap:)];
        [cell.updatextView addGestureRecognizer:tap];
        cell.delegate=self;
         return cell;
    }else{
        DBJAddIllCaseFourCell *cell=[tableView dequeueReusableCellWithIdentifier:identStr forIndexPath:indexPath];
        cell.delegate=self;
         return cell;
    }
}

/*返回行高的方法*/
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellHeight = 0;
    switch (indexPath.row) {
        case 0:
            cellHeight=45;
            break;
        case 1:
            cellHeight=45;
            break;
            
        case 2:
            cellHeight=160;
            break;
        case 3:
            cellHeight=self.view.bounds.size.height-(45+45+160);
            break;
    }
    
    return cellHeight;
}
#pragma mark -实现fourcell代理方法
/* fourcell代理方法 */
-(void)FourCellAddphotoWithCell:(DBJAddIllCaseFourCell *)fourCell{
    
    HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
    
    // 设置图像选择代理
    picker.pickerDelegate = self;
    // 设置目标图片尺寸
    picker.targetSize = CGSizeMake(60, 60);
    // 设置最大选择照片数量
    picker.maxPickerCount = 3;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark -实现hmdelagate方法

/* hmdelegate方法 */  //第4个cell
- (void)imagePickerController:(HMImagePickerController *)picker
      didFinishSelectedImages:(NSArray<UIImage *> *)images
               selectedAssets:(NSArray<PHAsset *> *)selectedAssets {
    
    // 记录图像，方便在 CollectionView 显示
    self.images = images;
    // 记录选中资源集合，方便再次选择照片定位
    self.selectedAssets = selectedAssets;
    
    NSIndexPath *index=[NSIndexPath indexPathForRow:3 inSection:0];
    DBJAddIllCaseFourCell *cell=[self.tableView cellForRowAtIndexPath:index];
    cell.iconImagesViews=self.images.mutableCopy;
    [self.secondeModel setObject:cell.iconImagesViews forKey:@"illIcons"];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -实现threecell的代理方法
-(void)addBtnTagCell:(DBJAddIllCaseThreeTabCell *)cell{
    //创建标签控制器
    DBJIllCaseTagViewController *tagTabVC=[[DBJIllCaseTagViewController alloc]initWithStyle:UITableViewStylePlain];
    tagTabVC.delegate=self; //设置代理
    [self.navigationController pushViewController:tagTabVC animated:YES];//推入控制器
}

#pragma mark -实现DBJIllCaseTagViewControllerDelegate
/* 标签云接口 */
-(void)sendTagWithCOntroller:(DBJIllCaseTagViewController *)tagVC tagList:(NSArray *)tagList{
    
//    //接受了选择的标签
//    DBJAddIllCaseThreeTabCell *cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
//    cell.tagsArry=tagList;
    NSLog(@"%@",tagList);
    DBJAddIllCaseThreeTabCell *threeCell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    threeCell.tagsArry=tagList;
    [self.secondeModel setObject:threeCell.tagsArry forKey:@"tagList"];
    NSString *desc=[threeCell getDescText];
    [self.secondeModel setObject:desc forKey:@"desc"];

    
}
#pragma mark -实现DBJAddIllCaseFirstTabCellDelegate

-(void)pushControllerWithCell:(DBJAddIllCaseFirstTabCell *)cell{
    
    if(cell.cellType==CellTypeFirst){
        
        DBJIllTypeTabViewController *illTypeVC=[[DBJIllTypeTabViewController alloc]initWithStyle:UITableViewStylePlain];
        [self.navigationController pushViewController:illTypeVC animated:YES];
        illTypeVC.delegate=self;
        
        //根据点击的cell序号push控制器
    }else if(cell.cellType==CellTypeSecond)
    {
        if(self.secondeModel[@"illType"]==nil){
            
            [DBJTools dbjShowSVErrorTitle:@"疾病类型不能为空" andTime:1];
            return ;
        }
        DBJIllTypeMinceViewController *minVC=[[DBJIllTypeMinceViewController alloc]initWithStyle:UITableViewStylePlain];
        minVC.urlNunber=self.illMinceList[self.selcetNum];
        minVC.delegate=self;
        [self.navigationController pushViewController:minVC animated:YES];
        
    }
    
}
#pragma mark -实现DBJIllTypeTabViewControllerDelegate代理方法

-(void)sendIlltype:(DBJIllTypeTabViewController *)VC WithType:(NSString *)typeStr index:(NSUInteger)index;{
    
    DBJAddIllCaseFirstTabCell *cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    cell.typeStr=typeStr;
    [self.secondeModel setObject:cell.typeStr forKey:@"illType"];
//    [self.tableView reloadData];
    cell.selectNumber=index;
    
    self.selcetNum=index;
}

#pragma mark -实现dbjMinceViewCOntrollerDelegate
//获取第二个cell的数据
-(void)sendMinceWithCell:(UITableViewCell *)cell WithTextStr:(NSString *)textStr{
    DBJAddIllCaseFirstTabCell *senondCell =[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    senondCell.typeStr=textStr;
    [self.secondeModel setObject:senondCell.typeStr forKey:@"illMince"];
}

#pragma mark -self.secondModel的懒加载方法

-(NSMutableDictionary *)secondeModel{
    if(_secondeModel==nil){
        _secondeModel=[NSMutableDictionary new];
        //获取时间标签
        NSString *timeStr=[self getTimeString];
        [_secondeModel setObject:timeStr forKey:@"timeDate"];
    }
    return _secondeModel;
}

#pragma mark -重写secndModel方法

-(void)setSecondTabmodel:(DBJSecondTabModel *)secondTabmodel{
    _secondTabmodel=secondTabmodel;
    for(NSUInteger i=0;i<4;i++){
        NSIndexPath *index=[NSIndexPath indexPathForRow:i inSection:0];
        if(i==0){
                DBJAddIllCaseFirstTabCell *cell=[self.tableView cellForRowAtIndexPath:index];
                cell.firstStr=secondTabmodel.illType;
            }else if(i==1){
                DBJAddIllCaseFirstTabCell *senCell=[self.tableView cellForRowAtIndexPath:index];
                senCell.typeStr=secondTabmodel.illMince;
                [self.tableView reloadData];
            }else if(i==2){
                DBJAddIllCaseThreeTabCell *threeCell=[self.tableView cellForRowAtIndexPath:index];
                threeCell.tagsArry=secondTabmodel.tagList;
                [self.tableView reloadData];
            }else{
                DBJAddIllCaseFourCell *fourCell=[self.tableView cellForRowAtIndexPath:index];
                fourCell.iconImagesViews=secondTabmodel.illIcons;
                [self.tableView reloadData];
            }
           [self.tableView reloadData];
        }
//    NSIndexPath *index=[NSIndexPath indexPathForRow:0 inSection:0];
//    DBJAddIllCaseFirstTabCell *cell=[self.tableView cellForRowAtIndexPath:index];
//    cell.typeStr=secondTabmodel.illType;
//    NSLog(@"%@",secondTabmodel.illType);
//    [self.tableView reloadData];
//    
}
#pragma mark -封装获取日期时间的方法

-(NSString *)getTimeString{
    NSDate *currentDate=[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];       //指定输出格式
    NSString *currentDateString = [formatter stringFromDate:currentDate];
    return currentDateString;
}

#pragma mark -实现tabView代理方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
        if(indexPath.row==0)
        {
            DBJIllTypeTabViewController *illTypeVC=[[DBJIllTypeTabViewController alloc]initWithStyle:UITableViewStylePlain];
            [self.navigationController pushViewController:illTypeVC animated:YES];
            illTypeVC.delegate=self;

            
        }else if(indexPath.row==1)
        {
            if(self.secondeModel[@"illType"]==nil){
                
                [DBJTools dbjShowSVErrorTitle:@"疾病类型不能为空" andTime:1];
                return ;
            }
            DBJIllTypeMinceViewController *minVC=[[DBJIllTypeMinceViewController alloc]initWithStyle:UITableViewStylePlain];
            minVC.urlNunber=self.illMinceList[self.selcetNum];
            minVC.delegate=self;
            [self.navigationController pushViewController:minVC animated:YES];
        }
}
#pragma mark -ThreeCell的TextView点击手势方法
/* 点击手势方法*/
-(void)clickTap:(UITapGestureRecognizer *)tap{
    DBJAddIllCaseThreeTabCell *cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    if ([cell.updatextView.text length] == 0) {
         cell.testViewsubLabel.text=@"";
        cell.testViewsubLabel.hidden=YES;
    }else{
        [ cell.testViewsubLabel setHidden:YES];
    }
    
}


@end
